import React, { useState } from 'react';
import { Form, Input, Button, message, Tabs, Space } from 'antd';
import { UserOutlined, LockOutlined, PhoneOutlined, SafetyOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import { useDispatch } from 'react-redux';
import { setToken, logout } from '../../store/slices/auth';
import { setMenus } from '../../store/slices/menu';
import { setMerchantList, setCurrentEntity, clearMerchantData } from '../../store/slices/merchant';
import { passwordLogin, verifyCodeLogin, sendSmsVerifycode } from '../../api/auth';
import { getMerchantIdentityList } from '../../api/merchant';
import navMenus from './menuData';
import './Login.less';

interface LoginForm {
    phone: string;
    password: string;
}

interface SmsLoginForm {
    phone: string;
    code: string;
}

const Login: React.FC = () => {
    const navigate = useNavigate();
    const dispatch = useDispatch();
    const [loading, setLoading] = useState(false);
    const [smsLoading, setSmsLoading] = useState(false);
    const [countdown, setCountdown] = useState(0);
    const [activeTab, setActiveTab] = useState('password');
    const [smsForm] = Form.useForm();

    // 发送验证码
    const sendSmsCode = async (phone: string) => {
        console.log('开始发送验证码，手机号:', phone);
        
        if (!phone) {
            message.error('请先输入手机号');
            return;
        }
        
        if (!/^1[3-9]\d{9}$/.test(phone)) {
            message.error('请输入正确的手机号');
            return;
        }

        setSmsLoading(true);
        try {
            console.log('调用发送验证码API...');
            // 调用发送验证码的API
            const response = await sendSmsVerifycode(phone);
            console.log('发送验证码API响应:', response);
            
            if (response) {
                message.success('验证码已发送');
                
                // 开始倒计时
                setCountdown(60);
                const timer = setInterval(() => {
                    setCountdown(prev => {
                        if (prev <= 1) {
                            clearInterval(timer);
                            return 0;
                        }
                        return prev - 1;
                    });
                }, 1000);
            } else {
                const errorMsg = response?.msg || '发送验证码失败';
                console.error('发送验证码失败:', errorMsg);
                message.error(errorMsg);
            }
        } catch (error: any) {
            console.error('发送验证码错误详情:', error);
            
            // 更详细的错误处理
            if (error.response) {
                console.error('服务器响应错误:', error.response.data);
                message.error(`服务器错误: ${error.response.data?.msg || error.response.statusText}`);
            } else if (error.request) {
                console.error('网络请求失败:', error.request);
                message.error('网络连接失败，请检查网络设置');
            } else {
                console.error('请求配置错误:', error.message);
                message.error(`请求失败: ${error.message}`);
            }
        } finally {
            setSmsLoading(false);
        }
    };

    // 处理登录成功后的逻辑
    const handleLoginSuccess = async (response: any) => {
        // 获取token
        const token = response?.token || response.token || '';
        
        // 直接使用本地菜单数据
        const menuData = navMenus;
        
        console.log("使用本地菜单数据:", menuData);
        
        if (!token) {
            message.error('登录成功但未获取到有效凭证');
            return false;
        }
        
        // 存储数据
        localStorage.setItem('token', token);
        localStorage.setItem('menuData', JSON.stringify(menuData));
        localStorage.setItem('userinfo', response.userinfo);
        
        // 更新Redux状态
        dispatch(setToken(token));
        dispatch(setMenus(menuData));

        // 调用商家身份列表接口
        try {
            const identityResponse = await getMerchantIdentityList();
            console.log("商家身份列表:", identityResponse);
            
            // 存储商家身份数据到Redux
            if (identityResponse && identityResponse.list) {
                dispatch(setMerchantList(identityResponse.list));
                
                // 设置当前选中的实体
                if (identityResponse.current_entity) {
                    dispatch(setCurrentEntity(identityResponse.current_entity));
                }
            }
            
            // 同时存储到localStorage作为备份
            localStorage.setItem('merchantIdentity', JSON.stringify(identityResponse));
        } catch (error) {
            console.error('获取商家身份列表失败:', error);
            
            // 清除登录信息
            dispatch(logout());
            dispatch(clearMerchantData());
            
            // 清除localStorage中的登录相关数据
            localStorage.removeItem('token');
            localStorage.removeItem('menuData');
            localStorage.removeItem('userinfo');
            localStorage.removeItem('merchantIdentity');
            localStorage.removeItem('currentMerchantEntity');
            
            message.error('获取商家身份信息失败，请重新登录');
            return false;
        }

        message.success(response.msg || '登录成功');
        
        // 确保导航是异步执行的最后一步
        setTimeout(() => {
            navigate('/home');
        }, 100);
        
        return true;
    };

    // 密码登录
    const handlePasswordLogin = async (values: LoginForm) => {
        setLoading(true);
        
        try {
            const response: any = await passwordLogin({
                phone: values.phone,
                password: values.password
            });
            console.log("登录响应:", response);
            
            // 检查登录是否成功
            if (response) {
                handleLoginSuccess(response);
            } else {
                message.error(response.msg || '登录失败，请检查用户名和密码');
            }
        } catch (error: any) {
            console.error('登录错误:', error);
        } finally {
            setLoading(false);
        }
    };

    // 短信验证码登录
    const handleSmsLogin = async (values: SmsLoginForm) => {
        setLoading(true);
        
        try {
            // 调用短信验证码登录的API
            const response: any = await verifyCodeLogin({
                phone: values.phone,
                code: values.code
            });
            
            console.log("短信登录响应:", response);
            
            // 检查登录是否成功
            if (response) {
                handleLoginSuccess(response);
            } else {
                message.error(response.msg || '验证码错误或已过期');
            }
        } catch (error: any) {
            console.error('短信登录错误:', error);
            message.error('验证码错误或已过期');
        } finally {
            setLoading(false);
        }
    };

    return (
        <div className="login-container">
            <div className="login-box">
                <div className="login-title">觉知生命后台管理系统</div>
                <div className="login-subtitle">欢迎登录</div>

                <Tabs
                    activeKey={activeTab}
                    onChange={setActiveTab}
                    centered
                    items={[
                        {
                            key: 'password',
                            label: '密码登录',
                            children: (
                                <Form
                                    name="passwordLoginForm"
                                    className="login-form"
                                    onFinish={handlePasswordLogin}
                                >
                                    <Form.Item
                                        name="phone"
                                        rules={[
                                            { required: true, message: '请输入用户名' },
                                            { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号' }
                                        ]}
                                    >
                                        <Input
                                            prefix={<UserOutlined />}
                                            placeholder="请输入手机号"
                                            size="large"
                                        />
                                    </Form.Item>

                                    <Form.Item
                                        name="password"
                                        rules={[{ required: true, message: '请输入密码' }]}
                                    >
                                        <Input
                                            prefix={<LockOutlined />}
                                            type="password"
                                            placeholder="请输入密码"
                                            size="large"
                                        />
                                    </Form.Item>

                                    <Form.Item>
                                        <Button
                                            type="primary"
                                            htmlType="submit"
                                            className="login-button"
                                            loading={loading}
                                            size="large"
                                            block
                                        >
                                            登录
                                        </Button>
                                    </Form.Item>
                                </Form>
                            )
                        },
                        {
                            key: 'sms',
                            label: '验证码登录',
                            children: (
                                <Form
                                    form={smsForm}
                                    name="smsLoginForm"
                                    className="login-form"
                                    onFinish={handleSmsLogin}
                                >
                                    <Form.Item
                                        name="phone"
                                        rules={[
                                            { required: true, message: '请输入手机号' },
                                            { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号' }
                                        ]}
                                    >
                                        <Input
                                            prefix={<PhoneOutlined />}
                                            placeholder="请输入手机号"
                                            size="large"
                                        />
                                    </Form.Item>

                                    <Form.Item
                                        name="code"
                                        rules={[{ required: true, message: '请输入验证码' }]}
                                    >
                                        <Space.Compact style={{ width: '100%' }}>
                                            <Input
                                                prefix={<SafetyOutlined />}
                                                placeholder="请输入验证码"
                                                size="large"
                                                style={{ flex: 1 }}
                                            />
                                            <Button
                                                size="large"
                                                loading={smsLoading}
                                                disabled={countdown > 0}
                                                onClick={async () => {
                                                    try {
                                                        // 验证手机号
                                                        await smsForm.validateFields(['phone']);
                                                        const phone = smsForm.getFieldValue('phone');
                                                        console.log('获取到手机号:', phone);
                                                        await sendSmsCode(phone);
                                                    } catch (error) {
                                                        console.error('验证手机号失败:', error);
                                                        message.error('请先输入正确的手机号');
                                                    }
                                                }}
                                            >
                                                {countdown > 0 ? `${countdown}s` : '获取验证码'}
                                            </Button>
                                        </Space.Compact>
                                    </Form.Item>

                                    <Form.Item>
                                        <Button
                                            type="primary"
                                            htmlType="submit"
                                            className="login-button"
                                            loading={loading}
                                            size="large"
                                            block
                                        >
                                            登录
                                        </Button>
                                    </Form.Item>
                                </Form>
                            )
                        }
                    ]}
                />

                {/* <div className="login-tips">
                    <div>游客账号同密码:admin</div>
                    <div>支持密码登录和手机验证码登录</div>
                </div> */}
            </div>
        </div>
    );
};

export default Login;